package cn.com.gridinfo.sooc.core.expand.callname.fragment;

import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.jeremy.arad.Arad;
import com.jeremy.arad.utils.Log;
import com.marshalchen.ultimaterecyclerview.UltimateRecyclerView;

import java.util.ArrayList;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;
import cn.com.gridinfo.sooc.R;
import cn.com.gridinfo.sooc.base.BaseSoocFragment;
import cn.com.gridinfo.sooc.common.LocalMark;
import cn.com.gridinfo.sooc.core.expand.callname.adapter.QueXiAdapter;
import cn.com.gridinfo.sooc.core.expand.callname.bean.Student;
import cn.com.gridinfo.sooc.core.expand.callname.common.CodeConst;
import cn.com.gridinfo.sooc.core.expand.callname.common.PageConst;
import cn.com.gridinfo.sooc.core.expand.callname.dao.CallNameDao;
import cn.com.gridinfo.sooc.utils.MessageUtils;

/**
 * 签到详情 缺席 Fragment
 * Created by yingchunli on 2015/12/8.
 */
public class QueXiFragment extends BaseSoocFragment {

    @InjectView(R.id.signinfo_list)
    UltimateRecyclerView signinfoList;//内容显示列表
    LinearLayoutManager linearLayoutManager;//布局管理器
    QueXiAdapter adapter;//适配器
    String ktid;//从activity传递过来的参数
    View view;//当前界面
    CallNameDao dao;
    @InjectView(R.id.text_siginfo)
    TextView textSiginfo;//缺席人数text
    @InjectView(R.id.count_ren_signinfo)
    TextView countRen;//人数
    @InjectView(R.id.count_ren_layout)
    LinearLayout countRenLayout;//显示人数的行
    int maxLastPositon;//数据最后位置
    String kcid;//课程id
    int delePosition;//要补签的人的位置
    @InjectView(R.id.noYdrs)
    LinearLayout noYdrs;//无应到人数 空白页提示
    @InjectView(R.id.hasYdrs)
    TextView hasYdrs;//有应到人数 空白页提示
    @InjectView(R.id.url_load)
    TextView url_blank;//

    public static QueXiFragment newInstance(String info) {
        Bundle args = new Bundle();
        QueXiFragment fragment = new QueXiFragment();
        args.putString("info", info);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        //判断Fragment中的ListView时候存在，判断该Fragment时候已经正在前台显示  通过这两个判断，就可以知道什么时候去加载数据了
        if (isVisibleToUser && isVisible()) {
            initData(); //加载数据的方法
        }
        super.setUserVisibleHint(isVisibleToUser);
    }

    void initData() {
        PageConst.pageNo = 1;
        PageConst.pageSize = 10;
        dao.LookClassInfo(ktid, PageConst.pageNo, PageConst.pageSize, CodeConst.EXPAND_SIGNINFO_QUEXI_PUSHDOWN);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.expand_signinfo_list, null);
        ButterKnife.inject(this, view);
        dao = new CallNameDao(this);
        //获取kcid  ktid
        String k[] = getArguments().getString("info").split(",");
        ktid = k[0];
        kcid = k[1];
        Log.d("缺席-》ktid" + ktid);
        Log.d("缺席-》kcid" + kcid);
        url_blank.setText(Arad.preferences.getString(LocalMark.SERVER_URL.getName())+"上传名单。");
        linearLayoutManager = new LinearLayoutManager(getActivity());
        signinfoList.setLayoutManager(linearLayoutManager);
        textSiginfo.setText("缺席人数: ");
        countRen.setTextColor(getResources().getColor(R.color.red_hint));//设置字体颜色
        countRenLayout.setVisibility(View.GONE);
        noYdrs.setVisibility(View.GONE);
        hasYdrs.setVisibility(View.VISIBLE);
        initView();
        return view;

    }

    @Override
    public void onRequestSuccess(int requestCode) {
        try {
            if (dao != null && dao.getStatus() != null) {
                if (dao.getStatus().equals("0")) {
                    switch (requestCode) {
//                        case CodeConst.EXPAND_SIGNINFO_QUEXI_FRIST:
//                            //获取签到详情成功
//                            initView();
//                            if (Integer.parseInt(dao.getClassInfo().getQsrs()) > 0) {
//                                if (countRenLayout != null) {
//                                    countRenLayout.setVisibility(View.VISIBLE);
//                                    countRen.setText(dao.getClassInfo().getQsrs());//设置人数
//                                    signinfoList.hideEmptyView();
//                                }
//                            } else {
//                                //无数据处理
//                                countRenLayout.setVisibility(View.GONE);
//
//                                //判断是否有应到人数
//                                if (Integer.parseInt(dao.getClassInfo().getYdrs()) > 0) {
//                                    //有应到人数
//                                    noYdrs.setVisibility(View.GONE);
//                                    hasYdrs.setVisibility(View.VISIBLE);
//                                } else {
//                                    //无应到人数
//                                    noYdrs.setVisibility(View.VISIBLE);
//                                    hasYdrs.setVisibility(View.GONE);
//                                }
//                                signinfoList.showEmptyView();
//
//                            }
//                            break;
                        case CodeConst.EXPAND_SIGNINFO_QUEXI_PUSHDOWN:
                            //下拉请求  刷新操作
                            signinfoList.setRefreshing(false);
                            if (dao.getStudentList() != null && !dao.getStudentList().isEmpty()) {
                                adapter.refresh(dao.getStudentList());
                                countRenLayout.setVisibility(View.VISIBLE);
                                countRen.setText(dao.getClassInfo().getQsrs());//设置人数
                                signinfoList.hideEmptyView();
                                adapter.loadNoDataView();
                            } else {
                                countRenLayout.setVisibility(View.GONE);
                                //判断是否有应到人数
                                if (Integer.parseInt(dao.getClassInfo().getYdrs()) > 0) {
                                    //有应到人数
                                    noYdrs.setVisibility(View.GONE);
                                    hasYdrs.setVisibility(View.VISIBLE);
                                } else {
                                    //无应到人数
                                    noYdrs.setVisibility(View.VISIBLE);
                                    hasYdrs.setVisibility(View.GONE);
                                }
                                //无数据处理
                                signinfoList.showEmptyView();
                            }
//                            if (dao.getStudentList().size() > (PageConst.pageSize - 1)) {
//                                adapter.loadMoreDataView();
//                            } else {
                            //数据小于当前页的话则不显示加载更多
//                                linearLayoutManager.scrollToPositionWithOffset(maxLastPositon, -1);
//                                linearLayoutManager.scrollToPosition(maxLastPositon);
//                            }
                            break;
                        case CodeConst.EXPAND_SIGNINFO_QUEXI_PULLUP:
                            if (dao.getStudentList() != null && !dao.getStudentList().isEmpty()) {
                                adapter.loadmore(dao.getStudentList());
                            } else {
                                //无数据则不显示下一页
                                adapter.loadNoDataView();
                                linearLayoutManager.scrollToPositionWithOffset(maxLastPositon, -1);
                            }
                            break;
                        case CodeConst.EXPAND_BUQIAN:
                            //补签成功
                            MessageUtils.showRightImageShortToast(getActivity(), "补签成功");
                            adapter.delete(delePosition);
                            if (countRen.getText().toString().trim().equals("1")) {
                                countRenLayout.setVisibility(View.GONE);
                            } else {
                                countRen.setText(Integer.parseInt(countRen.getText().toString()) - 1 + "");//设置人数
                            }
                            break;
                    }
                } else {
                    MessageUtils.showImageShortToast(getActivity(), dao.getStatusCode());
                }
            }
        } catch (Exception e) {
            MessageUtils.showImageShortToast(getActivity(), "请求数据异常");
        }
    }

    /**
     * 初始化界面数据
     */
    void initView() {
        List<Student> studentList = new ArrayList<>();
        adapter = new QueXiAdapter(studentList, getActivity());
        signinfoList.setAdapter(adapter);
        signinfoList.enableLoadmore();
        signinfoList.setDefaultOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                PageConst.pageNo = 1;//首页
                dao.LookClassInfo(ktid, PageConst.pageNo, PageConst.pageSize, CodeConst.EXPAND_SIGNINFO_QUEXI_PUSHDOWN);
                linearLayoutManager.scrollToPosition(0);
            }
        });
        signinfoList.setOnLoadMoreListener(new UltimateRecyclerView.OnLoadMoreListener() {
            @Override
            public void loadMore(final int itemsCount, final int maxLastVisiblePosition) {

//                if (itemsCount > (PageConst.pageSize - 1)) {
//                    maxLastPositon = maxLastVisiblePosition;
//                    dao.LookClassInfo(ktid, ++PageConst.pageNo, PageConst.pageSize, CodeConst.EXPAND_SIGNINFO_QUEXI_PULLUP);
//
//                } else {
//                    if (signinfoList != null)
//                        adapter.loadNoDataView();
//                    linearLayoutManager.scrollToPositionWithOffset(maxLastVisiblePosition, -1);
//                }
            }
        });
        // 补签
        adapter.setmOnItemClickLitener(new QueXiAdapter.OnItemClickListener() {
            @Override
            public void OnItemClick(View view, final int position) {
                new MaterialDialog.Builder(getActivity())
                        .content("确定要为" + adapter.getItemContent().get(position).getXm() + "补签吗？")
                        .backgroundColor(Color.WHITE)
                        .contentColor(getResources().getColor(R.color.color_tv333))
                        .positiveColor(getResources().getColor(R.color.colorAccent))
                        .positiveText(R.string.agree)
                        .onPositive(new MaterialDialog.SingleButtonCallback() {
                            @Override
                            public void onClick(MaterialDialog materialDialog, DialogAction dialogAction) {
                                dao.buQian(ktid, kcid, adapter.getItemContent().get(position).getXh(), "1",
                                        CodeConst.EXPAND_BUQIAN);
                                delePosition = position;
                            }
                        })
                        .show();
            }
        });
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.reset(this);
    }
}
